//
//  SetBeacon4ViewController.swift
//  MTBLETools
//
//  Created by 方强 on 16/10/24.
//  Copyright © 2016年 MT. All rights reserved.
//

import UIKit
import MTSDK

class SetBeacon4ViewController: UIViewController {
    
    class func getActivity() -> SetBeacon4ViewController{
        let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main);
        let vc = storyBoard.instantiateViewController(withIdentifier: "SetBeacon4ViewController") as! SetBeacon4ViewController;
        
        return vc;
    }

    var working_device:MTBLEDevice!;
    var pwd:String = "";
    private var mStaticDatas:StaticDatas!;
    override func viewDidLoad() {
        super.viewDidLoad()
        mStaticDatas = StaticDatas.getInstance();
        
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(keyboardHide));
        tapGestureRecognizer.cancelsTouchesInView = false;
        
        self.view.addGestureRecognizer(tapGestureRecognizer);
        
        // Do any additional setup after loading the view.
    }
    
    func keyboardHide(tap:UITapGestureRecognizer){
        self.view.endEditing(true);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 初始化控件
    private var baseAlert: UIAlertView!;
    @IBOutlet weak var parentView: UIView!
    @IBOutlet weak var beaconId_spinertmp: UIView!
    private let BEACONIDs = ["1","2","3"];
    private var beaconId_spiner: ISGDropDownList?
    @IBOutlet weak var major_edit: UITextField!
    @IBOutlet weak var minor_edit: UITextField!
    @IBOutlet weak var measure_edit: UITextField!
    @IBOutlet weak var sendweight_edit: UITextField!
    @IBOutlet weak var uuid_txt: UILabel!
    @IBOutlet weak var uuid_spinertmp: UIView!
    private var uuid_spiner: ISGDropDownList?
    @IBOutlet weak var sendhz_edit: UITextField!
    @IBOutlet weak var sendpower_spinertmp: UIView!
    private var sendpower_spiner: ISGDropDownList?
    @IBOutlet weak var newpwd_edit: UITextField!
    @IBOutlet weak var newpwd_check: UISwitch!
    @IBOutlet weak var version_txt: UILabel!
    private var uuidNames = [String]();
    
    // 初始化控件
    private func initView(){
        if(beaconId_spiner != nil){
            return;
        }
        
        beaconId_spiner = ISGDropDownList(frame: CGRect(x: beaconId_spinertmp.frame.minX, y: beaconId_spinertmp.frame.minY, width: beaconId_spinertmp.frame.width, height: beaconId_spinertmp.frame.height));
        beaconId_spiner!.listItems = BEACONIDs;
        beaconId_spiner!.reloadData();
        beaconId_spiner?.clickDropDown = {(index) in
            print("beaconId_spiner->\(index)");
            self.refreshPrivateData(index: index);
        };
        
        for uuid in mStaticDatas.uuidList {
            uuidNames.append(uuid.getName());
        }
        uuid_spiner = ISGDropDownList(frame: CGRect(x: uuid_spinertmp.frame.minX, y: uuid_spinertmp.frame.minY, width: uuid_spinertmp.frame.width, height: uuid_spinertmp.frame.height));
        uuid_spiner!.listItems = uuidNames;
        uuid_spiner!.reloadData();
        
        uuid_spiner?.clickDropDown = {(index) in
            self.uuid_txt.text = "UUID:\(self.mStaticDatas.uuidList[index].getUuid())";
        };
        
        sendpower_spiner = ISGDropDownList(frame: CGRect(x: sendpower_spinertmp.frame.minX, y: sendpower_spinertmp.frame.minY, width: sendpower_spinertmp.frame.width, height: sendpower_spinertmp.frame.height));
        sendpower_spiner!.listItems = MTBeacon4Base.SendPowerName;
        sendpower_spiner!.reloadData();
        self.parentView.addSubview(beaconId_spiner!);
        self.parentView.addSubview(uuid_spiner!);
        self.parentView.addSubview(sendpower_spiner!);
        
        initBLE();
    }
    
    // 刷新显示公共参数
    private var publicdata:MTBeaconInfModel?;
    private func refreshPublicData(){
        if(publicdata == nil){
            return;
        }
        
        sendhz_edit.text = "\(publicdata!.getSendhz())";
        sendpower_spiner?.selectedIndex = publicdata!.getSendpower();
        
        version_txt.text = "固件版本:\(publicdata!.getVersion()!)";
        
    }
    
    // 刷新显示私有参数
    private var privatedatas:[MTBeaconInfModel]?;
    private func refreshPrivateData(index:Int){
        if(privatedatas == nil){
            return;
        }
        let model = privatedatas![index];
        beaconId_spiner?.selectedIndex = index;
        major_edit.text = "\(model.getMajor())";
        minor_edit.text = "\(model.getMinor())";
        measure_edit.text = "\(model.getMeasuedPower())";
        sendweight_edit.text = "\(model.getWeight())";
        uuid_txt.text = "UUID:\(model.getBeaconUUID()!)";
        
        var findit = false;
        
        for i in 0 ..< mStaticDatas.uuidList.count {
            if(mStaticDatas.uuidList[i].getUuid() == model.getBeaconUUID()!){
                uuid_spiner?.selectedIndex = i;
                findit = true;
                break;
            }
        }
        
        if(!findit){ // 如果列表里面不存在这个uuid
            let newuuid = UuidAndName(name: "未命名", uuid: model.getBeaconUUID()!);
            newuuid.setId(id: UuidAndName.add(database: self.mStaticDatas.db, device: newuuid));
            self.mStaticDatas.uuidList.append(newuuid);
            self.uuidNames.append("未命名");
            self.uuid_spiner?.selectedIndex = self.uuidNames.count-1;
        }
    }
    
    // 显示失败对话框
    private func showFailAlert(erromsg: String){
        baseAlert = UIAlertView(title: "Fail", message: erromsg, delegate: nil, cancelButtonTitle: "OK");
        baseAlert.show();
    }
    
    // 初始化蓝牙
    private var manager:MTBLEManager!;
    private var ble:MTBeacon4Base!;
    private func initBLE(){
        manager = MTBLEManager.getInstance();
        ble = MTBeacon4Base(manager: manager);
        
        readInf();
    }
    
    // 同步信息
    private func readInf(){
        
        self.baseAlert = UIAlertView(title: "Inf", message: "同步数据。。。", delegate: nil, cancelButtonTitle: nil);  // 建立一个缓冲对话框
        self.baseAlert.show();
        
        let callback = MTBeacon4Base_ReadInfsCallBack();
        callback.onSuccess = { (ble, publicdata, privatedatas) in
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            
            self.publicdata = publicdata;
            self.privatedatas = privatedatas;
            
            self.refreshPublicData();
            self.refreshPrivateData(index: 0);
            
        };
        callback.onFail = {(ble, errocode) in
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "读取失败:\(errocode.getMsg())");
        };
        let errocode = ble.readAllInf(device: working_device, pwd: pwd, readinfscallback: callback);
        if(errocode.getCode() != 0){
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "读取失败:\(errocode.getMsg())");
        }
    }
    
    // 设置私有参数
    private func setPrivate(){
        let privateDatas = MTBeaconInfModel();
        privateDatas.setBeaconid(beaconid: beaconId_spiner!.selectedIndex);
        
        // major
        if((major_edit.text == nil) || (major_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (major_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 5)){
            self.showFailAlert(erromsg: "major erro");
            return;
        }
        let major = Int(major_edit.text!)!;
        if ((major<0) || (major>65535)) {
            self.showFailAlert(erromsg: "major erro");
            return;
        }
        privateDatas.setMajor(major: major);
        
        // minor
        if((minor_edit.text == nil) || (minor_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (minor_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 5)){
            self.showFailAlert(erromsg: "minor erro");
            return;
        }
        let minor = Int(minor_edit.text!)!;
        if ((minor<0) || (minor>65535)) {
            self.showFailAlert(erromsg: "minor erro");
            return;
        }
        privateDatas.setMinor(minor: minor);
        
        // measur
        if((measure_edit.text == nil) || (measure_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (measure_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 2)){
            self.showFailAlert(erromsg: "measure erro");
            return;
        }
        let measure = Int(measure_edit.text!)!;
        if ((measure<0) || (measure>99)) {
            self.showFailAlert(erromsg: "measure erro");
            return;
        }
        privateDatas.setMeasuedPower(measuedPower: measure);
        
        // 广播比重
        if((sendweight_edit.text == nil) || (sendweight_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (sendweight_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 2)){
            self.showFailAlert(erromsg: "measure erro");
            return;
        }
        let sendweight = Int(sendweight_edit.text!)!;
        if ((sendweight<0) || (sendweight>10)) {
            self.showFailAlert(erromsg: "广播比重 erro");
            return;
        }
        privateDatas.setWeight(weight: sendweight);
        
        // UUID
        let uuid = uuid_txt.text!.substring(from: uuid_txt.text!.index(uuid_txt.text!.startIndex, offsetBy: 5));
        print("uuid->\(uuid)");
        privateDatas.setBeaconUUID(beaconUUID: uuid);
        
        self.baseAlert = UIAlertView(title: "Inf", message: "设置私有参数。。。", delegate: nil, cancelButtonTitle: nil);  // 建立一个缓冲对话框
        self.baseAlert.show();
        
        let callback = MTBeacon4Base_BaseCallBack();
        callback.onSuccess = {(b) in
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
        };
        
        callback.onFail = {(b, errocode) in
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "设置错误:\(errocode.getMsg())");
        };
        
        let result = ble.setPrivateParamters(device: working_device, pwd: pwd, deviceinf: privateDatas, setprivatecallback: callback);
        if(result.getCode() != 0){
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "设置错误:\(result.getMsg())");
            return;
        }
    }
    
    // 设置公有参数
    private func setPublic(){
        let publicDatas = MTBeaconInfModel();
        
        // Hz
        if((sendhz_edit.text == nil) || (sendhz_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (sendhz_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 4)){
            self.showFailAlert(erromsg: "广播频率 erro");
            return;
        }
        let hz = Int(sendhz_edit.text!)!;
        if ((hz<100) || (hz>2000)) {
            self.showFailAlert(erromsg: "广播频率 erro");
            return;
        }
        publicDatas.setSendhz(sendhz: hz);
        
        // power
        publicDatas.setSendpower(sendpower: sendpower_spiner!.selectedIndex);
        
        // pwd
        if(newpwd_check.isOn){
            if((newpwd_edit.text == nil) || ((newpwd_edit.text!.lengthOfBytes(using: String.Encoding.utf8) != 0) && (newpwd_edit.text!.lengthOfBytes(using: String.Encoding.utf8) != 6))){
                self.showFailAlert(erromsg: "密码必须6位");
                return;
            }
            publicDatas.setNewpwd(newpwd: newpwd_edit.text!);
        }
        
        self.baseAlert = UIAlertView(title: "Inf", message: "设置公有参数。。。", delegate: nil, cancelButtonTitle: nil);  // 建立一个缓冲对话框
        self.baseAlert.show();
        
        let callback = MTBeacon4Base_BaseCallBack();
        callback.onSuccess = {(b) in
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
        };
        
        callback.onFail = {(b, errocode) in
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "设置错误:\(errocode.getMsg())");
        };
        
        let result = ble.setPublicParamters(device: working_device, pwd: pwd, deviceinf: publicDatas, setpubliccallback: callback);
        if(result.getCode() != 0){
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "设置错误:\(result.getMsg())");
            return;
        }
    }
    
    // 临时部署
    private func setUndevelop(){
        
        self.baseAlert = UIAlertView(title: "Inf", message: "临时部署。。。", delegate: nil, cancelButtonTitle: nil);  // 建立一个缓冲对话框
        self.baseAlert.show();
        
        let callback = MTBeacon4Base_BaseCallBack();
        callback.onSuccess = {(b) in
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
        };
        
        callback.onFail = {(b, errocode) in
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "临时部署错误:\(errocode.getMsg())");
        };
        let result = ble.setUndevelop(device: working_device, pwd: pwd, setundevelopcallback: callback);
        
        if(result.getCode() != 0){
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "临时部署错误:\(result.getMsg())");
            return;
        }
    }
    
    @IBAction func OnclickAction(_ sender: UIButton) {
        
        if(sender.tag == 1){  // 配置私有参数
            setPrivate();
            return;
        }
        if(sender.tag == 2){  // 配置公有参数
            setPublic();
            return;
        }
        if(sender.tag == 3){  // 临时部署
            setUndevelop();
            return;
        }
    }
    
    @IBAction func goBackAction(_ sender: UIBarButtonItem) {
        dismiss(animated: false, completion: nil);
    }

    @IBAction func pwdEnable(_ sender: UISwitch) {
        newpwd_edit.isEnabled = sender.isOn;
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    @IBAction func TextFinish(_ sender: UITextField) {
        sender.resignFirstResponder();
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        self.view.openKeyboardOffsetView();
        
        initView();
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated);
        self.view.closeKeyboardOffsetView();
    }

}
